from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.shortcuts import redirect
from common.models import User, Complain, Result
# 设置别名避免login函数名和视图名相同导致错误
from django.contrib.auth import logout, login as auth_login, authenticate
from django.contrib.auth.models import User
from django.contrib.auth import get_user_model

# Create your views here.

def main(request):
    # 取session
    username = request.session.get('username', '游客')
    return render(request, 'common/main.html', {'username': username})

def login(request):
    username = request.session.get('username', '游客')
    return render(request, 'common/login.html', {'username': username})

def showmain(request):
    # 获取账号密码
    username = request.POST.get('username')
    password = request.POST.get('password')
    # 验证
    user = authenticate(username=username, password=password)
    if user is not None:
        auth_login(request, user)
        # 存储session
        request.session['username'] = username
        request.session['password'] = password
        request.session.set_expiry(86400)

    return redirect('/common/main')

def quit(request):
    # 清除session
    logout(request)
    request.session.flush()
    return redirect('/common/main')

def registe(request):
    username = request.session.get('username', '游客')
    return render(request, 'common/registe.html', {'username': username})

def showregiste(request):
    # 获取表单信息
    username = request.POST.get('username')
    password = request.POST.get('password')
    first_name = request.POST.get('first_name')
    last_name = request.POST.get('last_name')
    email = request.POST.get('email')
    id_number = request.POST.get('id_number')
    mobile = request.POST.get('mobile')
    address = request.POST.get('address')
    # 注册
    User = get_user_model()
    User.objects.create_user(username=username, password=password, first_name=first_name, last_name=last_name,email=email, id_number=id_number, mobile=mobile, address=address)
    # 存储session
    request.session['username'] = username
    request.session['password'] = password
    request.session.set_expiry(86400)

    return redirect('/common/main')